use jni::objects::*;
use jni::objects::JString;
use jni::JNIEnv;
use active_win_pos_rs::get_active_window;
use jni::sys::{jboolean, jint};

const BK_PLAYER_TITLE: &str = "BkPlayer-wlh";
const EDGE: &str = "Microsoft Edge";
const CHROME: &str = "Google Chrome";

#[no_mangle]
pub unsafe extern "C" fn Java_com_gdnm_bkplayer_util_ActiveWindowUtilImpl_checkInject(_: JNIEnv, _class: JClass) {
    println!("inject success");
}

#[no_mangle]
pub unsafe extern "C" fn Java_com_gdnm_bkplayer_util_ActiveWindowUtilImpl_getActiveWindowName<'a>(env: JNIEnv<'a>, _class: JClass<'a>) -> JString<'a>{
    let result = match get_active_window() {
        Ok(active_window) => {
            active_window.app_name
        }
        Err(()) => {
            String::new()
        }
    };

    env.new_string(result).unwrap()
}

#[no_mangle]
pub unsafe extern "C" fn Java_com_gdnm_bkplayer_util_ActiveWindowUtilImpl_getActiveWindowTitle<'a>(env: JNIEnv<'a>, _class: JClass<'a>) -> JString<'a>{
    let result = match get_active_window() {
        Ok(active_window) => {
            active_window.title
        }
        Err(()) => {
            String::new()
        }
    };

    env.new_string(result).unwrap()
}

#[no_mangle]
pub unsafe extern "C" fn Java_com_gdnm_bkplayer_util_ActiveWindowUtilImpl_isAlwaysOnTop(_: JNIEnv, _class: JClass) -> jboolean{
    let (app_name, title) = match get_active_window() {
        Ok(active_window) => {
            (active_window.app_name, active_window.title)
        }
        Err(()) => {
            (String::new(), String::new())
        }
    };

    if app_name == EDGE || app_name == CHROME{
        true as jboolean
    }else if title == BK_PLAYER_TITLE{
        true as jboolean
    }else{
        false as jboolean
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_active_window() {
        match get_active_window() {
            Ok(active_window) => {
                println!("active window: {:#?}", active_window);
            }
            Err(()) => {
                println!("error occurred while getting the active window");
            }
        }
    }

}
